package com.shimao.celnet.payment.service.apiservice;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.shimao.celnet.payment.model.response.NotifyPay;
import com.shimao.celnet.payment.util.FinalUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.remoting.RemoteAccessException;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.TreeMap;


/*
 * 功能描述: 通联支付异步通知方法
 * @Author: Matt
 * @Date: 2019/5/20 16:28
 */
@Service
@Async("taskExecutor")
public class AsyncNotifyService {
    protected Logger logger = Logger.getLogger(this.getClass());
    @Autowired
    private RetryNotifyService retryNotifyService;
    @Async
    public void notifyTLCust(NotifyPay result, String url){
        Date a = new Date();
        logger.info("---------------------------通联支付结果异步通知开始"+(new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").format(a)));
        RestTemplate restTemplate = new RestTemplate();
        try{
            logger.info("---------------------------通联支付结果异步通知外部系统参数：url："+url+"--请求参数: {" +
                    "paymentId='" + result.getPaymentId() + '\'' +
                    ", userId='" + result.getUserId() + '\'' +
                    ", userName='" + result.getUserName() + '\'' +
                    ", payType='" + result.getPayType() + '\'' +
                    ", payAmount='" + result.getPayAmount() + '\'' +
                    ", payStartTime='" + result.getPayStartTime() + '\'' +
                    ", payEndTime='" + result.getPayEndTime() + '\'' +
                    ", payStatus='" + result.getPayStatus() + '\'' +
                    ", trxId='" + result.getTrxId() + '\'' +
                    ", sign='" + result.getSign() + '\'' +
                    ", paymentList=" + result.getPaymentList().toString() +
                    '}');

           /* ResponseEntity<NotifyResponse> resp = restTemplate.postForEntity(url,result, NotifyResponse.class);
            logger.info("---------------------------异步通知外部系统响应："+JSON.toJSONString(resp));
            if(!FinalUtil.ALLIN_SUCCESS_CODE.equals(resp.getBody().getErrcode())){
                throw new RemoteAccessException("返回值错误");
            }*/
            //获取外部系统响应结果
            JSONObject responseObject = new JSONObject();
            //创建HTTP 以及请求头
            HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
            CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
            //请求方式
            //o+异步通知 正式环境 notifyurl=https://interface.shimaowy.com:8443/shsm-action/sm/pay/refundSuccessCallBack
            HttpPost httpPost = new HttpPost(url);
            //设置参数
            TreeMap<String,String> headers = new TreeMap<String,String>();
            headers.put(FinalUtil.HEADER_CONTENT_TYPE,"application/json;charset=utf-8");

            //找到通知连接
            //拼凑回传连接
            StringEntity entity = new StringEntity(JSON.toJSONString(result), "utf-8");
            //entity.setContentEncoding("UTF-8");
            //实例化之后还需要再次设置一下ContentType 不然会默认修改格式为 text/plain
            entity.setContentType("application/json");
            httpPost.setEntity(entity);
            //请求外部系统
            //执行请求
            CloseableHttpResponse response = closeableHttpClient.execute(httpPost);
            //返回参数
            HttpEntity httpEntity = response.getEntity();
            responseObject = JSON.parseObject(EntityUtils.toString(httpEntity, "UTF-8"));
            logger.info("---------------------------异步通知外部系统响应："+responseObject.toString());

            if(!FinalUtil.ALLIN_SUCCESS_CODE.equals(responseObject.get("errcode"))){
                throw new RemoteAccessException("返回值错误");
            }
        }catch(Exception e){
            logger.debug("---------------------------异步通知外部系统异常："+e.getMessage());
            retryNotifyService.notifyRetry(result,url);
        }
        logger.info("---------------------------通联支付结果异步通知结束");
    }

}
